<?php

namespace App\HttpController;

use App\Utils\Code;
use EasySwoole\HttpAnnotation\AnnotationController;
use EasySwoole\HttpAnnotation\Exception\Annotation\ParamValidateError;
use EasySwoole\Validate\Validate;

class Common extends AnnotationController
{

    protected function onException(\Throwable $throwable): void
    {
        if($throwable instanceof ParamValidateError){
            /** @var Validate $validate */
            $validate = $throwable->getValidate();
            $errorMsg = $validate->getError()->getErrorRuleMsg();
            $errorCol = $validate->getError()->getField();
            $this->writeJson(Code::PARAM_IS_ERROR,null,"字段{$errorCol}--{$errorMsg}");
        }else{
            $this->writeJson(500,null,$throwable->getMessage());
        }
    }

    /**
     * 返回成功提示信息
     */
    protected function renderSuccess($msg = 'SUCCESS') : bool
    {
        $this -> writeJson(0, [], $msg);
        return true;
    }

    /**
     * 返回失败结果
     */
    protected function renderError($code = 1, $msg = '', $result = []) : bool
    {
        if (!$msg) $msg = Code::getMessage($code); 
        $this -> writeJson($code, $result = $result, $msg);
        return false;
    }

    /**
     * 返回数据
     */
    protected function renderSuccessData($result = []) : bool
    {
        $this -> writeJson(0, $result, 'SUCCESS');
        return true;
    }

}